import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { BladeContainerBase } from '../../../../shared/blade/blade-container-base';
import { BladeData } from '../../../../shared/blade/blade-data';
import { Blade } from '../../../../shared/blade/blade.model';
import { Command } from '../../../../shared/toolbar.service';
import { Tag } from '../../../../entity/tag.model';
import { DialogResult } from '../../../../shared/dialog.service';
import { TagService } from '../../../../service/tag.service';
import { TagEditComponent } from '../tag-edit/tag-edit.component';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { MatrixStateGroupListComponent } from '../../matrix-config/matrix-state-group-list/matrix-state-group-list.component';
import { Setofvalue } from '../../../../entity/setofvalue.model';
import { ApplicationService } from '../../../../service/application.service';
import { TurbComponent } from '../../../../entity/turbcomponent.model';
import { TurbcomponentService } from '../../../../service/turbcomponent.service';

@Component({
    selector: 'app-tag-list',
    templateUrl: './tag-list.component.html',
    styleUrls: ['./tag-list.component.css']
})
export class TagListComponent extends BladeContainerBase<Tag>{
    tag: Tag[] = [];
    blade: Blade;
    filterTags: Tag[];
    original: Tag[] = [];
    result: Tag[] = [];
    //
    turbComponentList: TurbComponent[] = [];
    originalTurbComponent: TurbComponent[] = [];
    //
    myForm: FormGroup;
    tagName: any;
    tagCode: any;
    showMes: boolean;
    onMoreShow = false;
    tagFilter: TagFilter;
    tagFilterData: TagFilterData = {
        turbineComponent: [],
        tagSets: [],
        // isTagDefinition: false,
        directPurchase: false
    };
    cols = [
        { field: 'tagName', header: '测点名称' },
        { field: 'tagDesc', header: '测点描述' },
        { field: 'tagCode', header: '测点编码' }
    ];
    constructor(
        private fb: FormBuilder,
        private tagService: TagService,
        private application: ApplicationService,
        private turbcomponentService: TurbcomponentService
    ) {
        super(fb);
        this.myForm = fb.group({
            tagCode: new FormControl('2'),
            tagName: new FormControl()
        });
        this.tagName = this.myForm.controls['tagName'];
        this.tagCode = this.myForm.controls['tagCode'];
        this.tagCode.valueChanges
            .debounceTime(300)
            .distinctUntilChanged()
            .subscribe((form: any) => {
                this.myForm.controls['tagName'].reset('');

            });
        this.tagName.valueChanges
            .debounceTime(300)
            .distinctUntilChanged()
            .subscribe((form: any) => {
                if (form) {
                    if (this.tagCode.value == 1) {//编码
                        this.tag = [...this.result.filter(o => o.tagCode.indexOf(form) > -1)];
                    } else if (this.tagCode.value == 2) {//名称
                        this.tag = [...this.result.filter(o => o.tagName.indexOf(form) > -1)];
                    }
                } else {

                    this.tag = [...this.result];
                }
                if (this.tag.length) {
                    this.showMes = false;
                    this.filterTag();
                } else {
                    this.showMes = true;
                }

            });
    }

    // tslint:disable-next-line:use-life-cycle-interface
    ngOnInit() {
        this.turbComponentList = [];
        const tagSets: Setofvalue[] = [...this.application.setKeyDict['TagSet']];
        this.tagFilter = {
            turbineComponent: [],
            tagSets: tagSets,
            // isTagDefinition: false,
            directPurchase: false
        }
        // let turbComponentList: Setofvalue[] = [...this.application.setKeyDict['TurbineComponent']];
        this.turbcomponentService.getParentTurbComponents()
            .then(res => {
                if (!res) { return false; };
                this.originalTurbComponent = [...res];

                this.turbComponentList = this.originalTurbComponent;
                this.tagFilter.turbineComponent = [...res];
            })
            .catch(error => this.bladeData.error = error)
            .then(res => this.bladeData.isLoading = false);

        this.showMes = false;
        this.commands = [
            new Command('add', '添加', 'fa fa-plus', 'setofkey:insert', blade => this.exeAdd(blade), blade => this.canExeAdd(blade)),
            new Command('edit', '编辑', 'fa fa-edit', 'setofkey:update', blade => this.exeEdit(blade), blade => this.canExeEdit(blade)),
            new Command('delete', '删除', 'fa fa-trash-o', 'setofkey:delete', blade => this.exeDelete(blade), blade => this.canDelete(blade)),
            new Command('config', '配置', 'fa fa-gears', 'setofkey:config', blade => this.exeConfig(blade), blade => this.canConfig(blade)),
        ];
        super.ngOnInit();
    }
    /**
       * 初始化数据
       *
       *
       * @memberof DicKeyListComponent
       */
    initData(): any | Observable<any> | Promise<any> {

        this.tagService 
            .getTagList()
            .then(res => {
                if (res && res.length) {
                    this.original = [...res];
                    this.tag = [...this.original];
                    this.result = [...this.tag];
                    this.filterTag();
                } else {
                    throw new Error('查询失败！');
                }
            })
            .catch(error => this.bladeData.error = error)
            .then(res => this.bladeData.isLoading = false);
    }
    exeAdd(blend: Blade): void {
        const data: BladeData = new BladeData();
        data.id = 'tagKeyCreate';
        data.title = '创建一个测点信息';
        data.subtitle = '创建一个测点信息';
        data.isClosingDisabled = false;
        this.blade = this.bladeService.createBlade(TagEditComponent, data, true, null, this.originalTurbComponent);
        this.bladeService.showBlade(this.blade, this.currentBlade);
    }

    canExeAdd(blend: Blade): boolean {
        return true;
    }
    exeEdit(blend: Blade): void {
        if (this.currentEntity != undefined) {
            const data: BladeData = new BladeData();
            data.id = 'turbaKeyEdit';
            data.title = this.currentEntity.tagName;
            this.blade = this.bladeService.createBlade(TagEditComponent, data, false, this.currentEntity, this.originalTurbComponent);
            this.currentBlade.bladeService.showBlade(this.blade, this.currentBlade);
        }
    }
    canExeEdit(blend?: Blade): boolean {
        return this.currentEntity != null;
    }
    exeDelete(blend: Blade): void {
        const selectedKeys = this.getSelected();
        if (selectedKeys.length > 0) {
            this.dialogService
                .showConfirmationDialog('确认删除', '是否要删除选中项？')
                .subscribe(dialogResult => {
                    if (dialogResult == DialogResult.Ok) {
                        this.currentBlade.bladeData.isLoading = true;
                        this.tagService.batchDelete(selectedKeys.map(o => o.tagId))
                            .then(res => {
                                if (res) {
                                    super.refresh(undefined);
                                }
                            })
                            .catch(error => this.bladeData.error = error)
                            .then(res => this.bladeData.isLoading = false);
                    }
                })
        }
    }
    canDelete(blend?: Blade): boolean {
        return this.getSelected().length > 0;
    }

    //状态组配置
    exeConfig(blend: Blade) {
        // let tag = blend.currentEntity.tagSet;
        // let index = tag.indexOf('02');
        if (this.currentEntity != undefined) {
            const data: BladeData = new BladeData();
            data.id = 'showMatrixStateGroupList';
            data.title = this.currentEntity.tagName + '矩阵状态组';
            data.isClosingDisabled = false;
            this.blade = this.bladeService.createBlade(MatrixStateGroupListComponent, data, false, null, this.currentEntity);
            this.bladeService.showBlade(this.blade, this.currentBlade);
        }
    }

    canConfig(blend: Blade) {
        //当测点选中矩阵时可配置
        // let tag: Tag = blend.currentEntity;
        // if (tag != null && tag.tagSet != undefined) {
        //     let t = tag.tagSet;
        //     let index = t.indexOf('02');
        //     return index > -1
        // }
        // return false
        return this.currentEntity != null;
    }

    /**
     * 单选
     *
     * @param {any} event
     * @param {any} key
     *
     * @memberof DicKeyListComponent
     */
    onItemCheack(event: HTMLInputElement, key: Tag) {
        console.log(key)
        key.isChecked = event.checked;
    }
    /**
     * 全选/全不选
     *
     * @param {HTMLInputElement} event
     *
     * @memberof DicKeyListComponent
     */
    onAllCheack(event: HTMLInputElement) {
        if (this.tag.length > 0) {
            for (let i = 0; i < this.tag.length; i++) {
                this.tag[i].isChecked = event.checked;
            }
        }
    }
    onSeletedChange(selectedKey: Tag) {
        if (this.currentBlade.childrenCanDeactivate()) {
            this.currentEntity = selectedKey;
        }
    }
    /**
     * 展开测点信息详情列表弹出层
     *
     * @param {Tag} selectedKey
     *
     * @memberof TagListComponent
     */
    showTagDetailsBlade(selectedKey: Tag) {
        if (this.currentEntity != selectedKey
            || this.bladeService.findBlade('tagDetailsBlade') == undefined) {
            const data: BladeData = new BladeData();
            data.id = 'tagDetailsBlade';
            data.title = selectedKey.tagName;
            data.isClosingDisabled = false;
            this.blade = this.bladeService.createBlade(TagEditComponent, data, false, selectedKey);
            this.bladeService.showBlade(this.blade, this.currentBlade).then(res => {
                if (res) {
                    this.currentEntity = selectedKey;
                }
            });

        }
    }
    /**
    * 获得选中项
    *
    * @returns {Setofkey[]}
    *
    * @memberof DicKeyListComponent
    */
    getSelected(): Tag[] {
        if (this.tag.length > 0) {
            const filter = this.tag.filter(ref => ref.isChecked);
            return filter == null ? [] : filter;
        }
        return [];
    }
    refresh() {
        super.refresh(undefined);
        this.myForm.controls['tagName'].reset('');
    }
    onMore() {
        if (!this.onMoreShow) { return this.onMoreShow = true; };
        this.onClose();

    }
    filterTag() {
        let result: Tag[] = [];
        if (this.tagFilterData.turbineComponent.length) {
            this.tagFilterData.turbineComponent.forEach(turbineComponent => {
                result = result.concat(this.tag.filter(tag => tag.turbComponentId == turbineComponent));
            })
        } else {
            result = [...this.tag];
        }
        let setTags: Tag[] = [];
        if (this.tagFilterData.tagSets.length) {
            this.tagFilterData.tagSets.forEach(tagSet => {
                setTags = setTags.concat(result.filter(o => o.tagSet && (o.tagSet.indexOf(tagSet) > -1)))
            });
            result = [...setTags];
        }
        // let tagDefinition: Tag[] = [];
        // if (this.tagFilterData.isTagDefinition && this.tagFilterData.directPurchase) {
        //     tagDefinition = tagDefinition.concat(result.filter(o => (o.tagDefinition == false) || (o.tagDefinition == true)));
        // } else {
        //     if (this.tagFilterData.isTagDefinition) {
        //         tagDefinition = tagDefinition.concat(result.filter(o => o.tagDefinition == false));
        //     };
        //     if (this.tagFilterData.directPurchase) {
        //         tagDefinition = tagDefinition.concat(result.filter(o => o.tagDefinition == true));
        //     }
        // }

        // if (this.tagFilterData.directPurchase || this.tagFilterData.isTagDefinition) {
        //     result = [...tagDefinition];
        // }
        this.filterTags = [...result];
    }
    onClick(item: Setofvalue) {
        item.isChecked = !item.isChecked;
    }
    onClose() {
        this.tagFilter.turbineComponent.forEach(v => {
            v.isChecked = false;
            const index = this.tagFilterData.turbineComponent.findIndex(o => o == v.turbComponentId);
            if (index > -1) {
                v.isChecked = true;
            }
        });
        this.tagFilter.tagSets.forEach(v => {
            v.isChecked = false;
            const index = this.tagFilterData.tagSets.findIndex(o => o == v.valueCode);
            if (index > -1) {
                v.isChecked = true;
            }
        });
        // this.tagFilter.isTagDefinition = this.tagFilterData.isTagDefinition;
        this.onMoreShow = false;
    }
    onSave() {
        this.tagFilterData.turbineComponent = []
        this.tagFilterData.tagSets = [];
        // this.tagFilterData.isTagDefinition = false;
        this.tagFilterData.directPurchase = false;
        this.tagFilter.turbineComponent.forEach(turbineComponent => {
            if (turbineComponent.isChecked) {
                this.tagFilterData.turbineComponent.push(turbineComponent.turbComponentId);
            }
        });
        this.tagFilter.tagSets.forEach(tagSet => {
            if (tagSet.isChecked) {
                this.tagFilterData.tagSets.push(tagSet.valueCode);
            }
        });
        // this.tagFilterData.isTagDefinition = this.tagFilter.isTagDefinition;
        this.tagFilterData.directPurchase = this.tagFilter.directPurchase;
        this.onMoreShow = false;
        this.bladeService.checkChangeCloseBlade(this.blade);
        this.filterTag();
    }
    onRowSelect(ev) {
    }
}
interface TagFilter {
    // turbineComponent: Setofvalue[];
    turbineComponent: TurbComponent[];
    tagSets: Setofvalue[];
    // isTagDefinition: boolean;
    directPurchase: boolean;
}
interface TagFilterData {
    // turbineComponent: string[];
    turbineComponent: number[];
    tagSets: string[];
    // isTagDefinition: boolean;
    directPurchase: boolean;
}



// WEBPACK FOOTER //
// ./src/app/module/basic/tag/tag-list/tag-list.component.ts